package com.yyw.rabbitmq.core.serialize.conver;

import com.google.common.base.Preconditions;
import com.yyw.rabbitmq.core.serialize.Serialize;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

/**
 * @author yiyw
 * @ClassName GenericMessageConverter.java
 * @Description TODO
 * @createTime 2021年07月28日 23:28:00
 */
public class GenericMessageConverter implements MessageConverter {

    private Serialize serialize;

    public GenericMessageConverter(Serialize serialize) {
        Preconditions.checkNotNull(serialize);
        this.serialize = serialize;
    }

    /**
     * 发送消息的时候，需要把我们的 Message 序列化为Byte[] 并且赋值到 amqp的Message中去
     *
     * @param o
     * @param messageProperties
     * @return
     * @throws MessageConversionException
     */
    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        return new Message(serialize.serializeRaw(o), messageProperties);
    }

    /**
     * 接收到消息后，需要将 amqp的Message中取出 body 转化为 我们自己的 Message
     *
     * @param message
     * @return
     * @throws MessageConversionException
     */
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        return serialize.deserialize(message.getBody());
    }
}
